package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.SubmitOrderProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderHistoryVO;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SubmitOrderProperties submitOrderProperties;
    @Autowired
    private WebSocketServer webSocketServer;

    public static final String URL ="https://api.map.baidu.com/geocoding/v3";
    public static final String URL1 ="https://api.map.baidu.com/directionlite/v1/riding";

    /**
     * 用户提交订单
     * @param ordersSubmitDTO
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1、处理业务异常（地址簿为空、购物车为空）
        //判断当前用户的地址簿是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }else {
            //查看地址是否超出配送范围
            //1、获取商家经纬度
            Object busslngandLat = getLngandLat(submitOrderProperties.getAddress());
            JSONObject jsonObject1 = JSON.parseObject(busslngandLat.toString());
            Double busslng = Double.valueOf(jsonObject1.getString("lng"));
            //保留小数点后六位
            String newbusslng = String.format("%.6f", busslng);
            Double busslat = Double.valueOf(jsonObject1.getString("lat"));
            String newbusslat = String.format("%.6f", busslat);
            //2、获得用户经纬度
            Object userlngandLat = getLngandLat(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
            JSONObject jsonObject2 = JSON.parseObject(userlngandLat.toString());
            Double userlng = Double.valueOf(jsonObject2.getString("lng"));
            String newuserlng = String.format("%.6f", userlng);
            Double userlat = Double.valueOf(jsonObject2.getString("lat"));
            String newuserlat = String.format("%.6f", userlat);
            //3、计算距离
            String bussaddress = newbusslat + "," + newbusslng;
            String useraddress = newuserlat + "," + newuserlng;
            Integer distance = getDistance(bussaddress, useraddress);

            //4、判断距离是否超过五公里
            if(distance>submitOrderProperties.getDistance()){
                //5、超出距离，给出异常
                throw new AddressBookBusinessException(MessageConstant.ADDRESS_OVER);
            }

        }
        //判断当前用户的购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);

        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if(shoppingCartList==null || shoppingCartList.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //2、向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());

        orderMapper.insert(orders);

        //3、向订单明细表插入n条数据
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insert(orderDetails);

        //4、清空购物车
        shoppingCartMapper.cleanByUserId(userId);
        //5、封装结果到VO中
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .build();

        return orderSubmitVO;
    }

    /**
     * 获取经纬度
     * @param address
     * @return
     */
    private Object getLngandLat(String address){

        HashMap<String,String> map = new HashMap<>();
        map.put("address",address);
        map.put("ak",submitOrderProperties.getAk());
        map.put("output","json");
        //map.put("callback","showLocation");
        String s= HttpClientUtil.doGet(URL, map);

        //String result = s.substring(27, s.length() - 1);

        JSONObject jsonObject = JSON.parseObject(s);
        JSONObject result1 = jsonObject.getJSONObject("result");

        Object location = result1.get("location");
        return location;
    }

    /**
     * 获取两地距离
     * @return
     */
    private Integer getDistance(String bussAddress , String userAddress){

        HashMap<String, String> map = new HashMap<>();
        map.put("origin",bussAddress);
        map.put("ak",submitOrderProperties.getAk());
        map.put("destination", userAddress);
        String s = HttpClientUtil.doGet(URL1, map);

        JSONObject jsonObject = JSON.parseObject(s);

        //检查地址是否正确
        Integer status = Integer.valueOf(jsonObject.getString("status"));
        if(status != 0){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_ERROR);
        }
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray routes = (JSONArray) result.get("routes");

        Integer distance =(Integer)((JSONObject)routes.get(0)).get("distance");
        return distance;
    }




    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向浏览器推送消息
        Map map = new HashMap();
        map.put("type",1);//1:表示来单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+ordersPaymentDTO.getOrderNumber());

        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
        return null;
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向浏览器推送消息
        Map map = new HashMap();
        map.put("type",1);//1:表示来单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);

        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 历史订单查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult historyOrdersByPage(Integer page, Integer pageSize, Integer status) {
        //开启分页查询
        PageHelper.startPage(page, pageSize);

        Page<OrderHistoryVO> orderHistoryVOS = new Page<>();
        //List<OrderHistoryVO> orderHistoryVOS = new ArrayList<>();

        //1、查询所有订单
        Long userId = BaseContext.getCurrentId();
        List<Orders> orderslist = orderMapper.getOrdersByUserId(userId,status);
        //2、查询每一个订单对应的菜品明细信息（集合）
        for (Orders order : orderslist) {
            OrderHistoryVO orderHistoryVO = new OrderHistoryVO();
            Long orderId = order.getId();
            List<OrderDetail> orderDetailList = orderDetailMapper.getDetailByOrderId(orderId);
            BeanUtils.copyProperties(order,orderHistoryVO);
            orderHistoryVO.setOrderDetailList(orderDetailList);
            //3、将上面两条信息添加到VOS中
            orderHistoryVOS.add(orderHistoryVO);
        }

        //封装结果
        long total = orderHistoryVOS.getTotal();
        List<OrderHistoryVO> result = orderHistoryVOS.getResult();

        //return new PageResult(orderHistoryVOS.size(),orderHistoryVOS);
        return new PageResult(total,result);
    }

    /**
     * 根据订单id查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderHistoryVO getOrderById(Integer id) {
        OrderHistoryVO orderHistoryVO = new OrderHistoryVO();
        //1、查询该订单信息
        Long userId = BaseContext.getCurrentId();
        Orders orders = orderMapper.getOrderByUserAndId(id,userId);
        BeanUtils.copyProperties(orders,orderHistoryVO);
        //2、根据订单id查询明细表
        List<OrderDetail> orderDetailList = orderDetailMapper.getDetailByOrderId(orders.getId());
        orderHistoryVO.setOrderDetailList(orderDetailList);
        //3、封装结果返回
        return orderHistoryVO;
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void getAnotherOrder(Long id) {
        //查询当前订单的详情信息
        List<OrderDetail> orderDetail = orderDetailMapper.getDetailByOrderId(id);
        if(orderDetail != null && orderDetail.size() != 0){
            //将订单中的商品添加至购物车
            for (OrderDetail detail : orderDetail) {
                ShoppingCart shoppingCart = new ShoppingCart();
                BeanUtils.copyProperties(detail,shoppingCart);
                shoppingCart.setUserId(BaseContext.getCurrentId());
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCartMapper.insert(shoppingCart);
            }
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        //1、获取订单信息
        Orders orders = orderMapper.getOrderByUserAndId(Math.toIntExact(id), BaseContext.getCurrentId());
        //2、判断订单支付状态，
        if(orders.getPayStatus()==Orders.UN_PAID && orders.getStatus()==Orders.PENDING_PAYMENT ){
            //未支付->直接设置取消状态
            orders.setStatus(Orders.CANCELLED);
            orderMapper.update(orders);
        }else if(orders.getPayStatus()==Orders.PAID && orders.getStatus()==Orders.TO_BE_CONFIRMED){
            //3、已支付，待接单->设置取消状态且退款
            orders.setStatus(Orders.CANCELLED);
            orderMapper.update(orders);
            log.warn("给用户退款");
        }
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getOrderById(id);

        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
